﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Linq;
using Pipra.Math;
using Pipra.Math.Geometry;

namespace Pipra.Gis.Transformation
{
    public class GeographicGeocentricTransformation :
        ITransformation<LatLon, Point3>,
        ITransformation<LatLonH, Point3>,
        ICoordinateOperationInfo
    {
        protected readonly double MajorAxis;
        protected readonly double MinorAxis;
        protected readonly double ESq;
        protected readonly double ESecSq;
        protected readonly double OneMinusESq;
        /// <summary>
        /// The spheroid.
        /// </summary>
        public readonly ISpheroid<double> Spheroid;

        public class GeocentricGeographicTransformation :
            ITransformation<Point3, LatLon>,
            ITransformation<Point3, LatLonH>,
            ICoordinateOperationInfo
        {

			public readonly GeographicGeocentricTransformation Core;

            private readonly double eSqMajAxis;
            private readonly double eSecSqMinAxis;

            internal GeocentricGeographicTransformation(GeographicGeocentricTransformation core)
            {
				Core = core;
			    eSqMajAxis = Core.ESq*Core.MajorAxis;
			    eSecSqMinAxis = Core.ESecSq*Core.MinorAxis;
                if (
                    0 == Core.MinorAxis
                )
                {
                    throw new ArgumentException("Core cannot be inverted.");
                }
			}


            LatLon ITransformation<Point3, LatLon>.TransformValue(Point3 geocentric)
            {
                double p = System.Math.Sqrt((geocentric.X * geocentric.X) + (geocentric.Y * geocentric.Y));
                double cosQ = System.Math.Atan((geocentric.Z * Core.MajorAxis) / (p * Core.MinorAxis));
                double sinQ = System.Math.Sin(cosQ);
                cosQ = System.Math.Cos(cosQ);
                return new LatLon(
                    System.Math.Atan(
                        (geocentric.Z + (eSecSqMinAxis * sinQ * sinQ * sinQ))
                        /
                        (p - (eSqMajAxis * cosQ * cosQ * cosQ))
                    ),
                    System.Math.Atan(geocentric.Y / geocentric.X) // atan2?
                );
            }

            public LatLonH TransformValue(Point3 geocentric)
            {
                double p = System.Math.Sqrt((geocentric.X * geocentric.X) + (geocentric.Y * geocentric.Y));
                double cosQ = System.Math.Atan((geocentric.Z * Core.MajorAxis) / (p * Core.MinorAxis));
                double sinQ = System.Math.Sin(cosQ);
                cosQ = System.Math.Cos(cosQ);
                double lat = System.Math.Atan(
                    (geocentric.Z + (eSecSqMinAxis * sinQ * sinQ * sinQ))
                    /
                    (p - (eSqMajAxis * cosQ * cosQ * cosQ))
                );
                sinQ = System.Math.Sin(lat);
                return new LatLonH(
                    lat,
                    System.Math.Atan(geocentric.Y / geocentric.X), // atan2?
                    (p / System.Math.Cos(lat))
                    - (
                        Core.MajorAxis / System.Math.Sqrt(
                            1.0 - (Core.ESq * sinQ * sinQ)
                        )
                    )
                );
            }

            IEnumerable<LatLon> ITransformation<Point3, LatLon>.TransformValues(IEnumerable<Point3> values)
            {
                return values.Select(((ITransformation<Point3, LatLon>)this).TransformValue);
            }

            public IEnumerable<LatLonH> TransformValues(IEnumerable<Point3> values)
            {
                return values.Select(TransformValue);
            }

            public bool HasInverse
            {
                get { return true; }
            }

            public ITransformation GetInverse()
            {
                return Core;
            }

            ITransformation<LatLon, Point3> ITransformation<Point3, LatLon>.GetInverse()
            {
                return Core;
            }

            ITransformation<LatLonH, Point3> ITransformation<Point3, LatLonH>.GetInverse()
            {
                return Core;
            }

            public string Name
            {
                get { return "Geocentric To Ellipsoid"; }
            }


            public IEnumerable<INamedParameter> GetParameters()
            {
                return Core.GetParameters();
            }
        }

        public GeographicGeocentricTransformation(
			ISpheroid<double> spheroid
		) {
			if (null == spheroid) {
				throw new ArgumentNullException("spheroid");
			}
			MajorAxis = spheroid.A;
			MinorAxis = spheroid.B;
			ESq = spheroid.ESquared;
			ESecSq = spheroid.ESecondSquared;
			OneMinusESq = 1.0 - ESq;
		}

		public Point3 TransformValue(LatLon geographic) {
			double sinLat = System.Math.Sin(geographic.Lat);
			double v = MajorAxis / System.Math.Sqrt(
				1.0 - (ESq * sinLat * sinLat)
			);
			double vcl = v * System.Math.Cos(geographic.Lat);
			return new Point3(
				vcl * System.Math.Cos(geographic.Lon),
				vcl * System.Math.Sin(geographic.Lon),
				OneMinusESq * v * sinLat
			);
		}

		public Point3 TransformValue(LatLonH geographic) {
			double sinLat = System.Math.Sin(geographic.Lat);
			double v = MajorAxis / System.Math.Sqrt(
				1.0 - (ESq * sinLat * sinLat)
			);
			double vhcl = (v + geographic.Height) * System.Math.Cos(geographic.Lat);
			return new Point3(
				vhcl * System.Math.Cos(geographic.Lon),
				vhcl * System.Math.Sin(geographic.Lon),
				((OneMinusESq * v) + geographic.Height) * sinLat
			);
		}

        public IEnumerable<Point3> TransformValues(IEnumerable<LatLon> values)
        {
            return values.Select(TransformValue);
        }


        public IEnumerable<Point3> TransformValues(IEnumerable<LatLonH> values)
        {
            return values.Select(TransformValue);
        }

        public bool HasInverse {
            get { return 0 != MinorAxis; }
		}

        public GeocentricGeographicTransformation GetInverse()
        {
            return new GeocentricGeographicTransformation(this);
        }

        ITransformation ITransformation.GetInverse()
        {
            return GetInverse();
		}

        ITransformation<Point3, LatLon> ITransformation<LatLon, Point3>.GetInverse()
        {
            return GetInverse();
		}

        ITransformation<Point3, LatLonH> ITransformation<LatLonH, Point3>.GetInverse()
        {
            return GetInverse();
		}

        public IEnumerable<INamedParameter> GetParameters()
        {
            return new INamedParameter[]
                {
                    new NamedParameter<double>("semi major", MajorAxis),
                    new NamedParameter<double>("semi minor", MinorAxis)
                };
        }

        public string Name
        {
            get { return "Ellipsoid To Geocentric"; }
        }
    }
}
